<template>
  <div class="teaching-display">
    <div class="display-container">
      <div class="display-header">
        <div class="header-content">
          <h1 class="page-title">设备调试信息展示</h1>
          <div class="header-actions">
            <el-button 
              type="danger" 
              @click="clearAllData" 
              class="clear-button"
              :icon="Delete"
            >
              清空所有数据
            </el-button>
          </div>
        </div>
      </div>

      <div class="table-container">
        <el-table
          :data="tableData"
          :span-method="arraySpanMethod"
          border
          style="width: 100%"
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
          :row-class-name="tableRowClassName"
          v-loading="loading"
          class="custom-table"
        >
          <el-table-column 
            label="组别" 
            prop="group" 
            width="100" 
            align="center"
            fixed="left"
          />
          <el-table-column 
            label="手动模式调试工作内容" 
            align="center"
            class-name="content-column"
          >
            <el-table-column 
              label="调试项目" 
              prop="project" 
              width="180" 
              align="center"
              show-overflow-tooltip
            />
            <el-table-column 
              label="调试内容" 
              prop="content" 
              width="180" 
              align="center"
              show-overflow-tooltip
            />
          </el-table-column>
          <el-table-column 
            label="调试情况记录" 
            align="center"
            class-name="record-column"
          >
            <el-table-column 
              label="调试方法 (关键词)" 
              prop="question" 
              min-width="220" 
              align="center"
              show-overflow-tooltip
            />
            <el-table-column 
              label="调试问题及注意事项" 
              prop="answer" 
              min-width="220" 
              align="center"
              show-overflow-tooltip
            />
            <el-table-column 
              label="备注" 
              prop="remark" 
              width="120" 
              align="center"
              show-overflow-tooltip
            />
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { getAllTeachingInfo, clearTeachingTable } from '../api'

const loading = ref(false)
const rawData = ref([])
const tableData = ref([])
let refreshInterval = null

const deviceMap = {
  1: '光电传感器调试',
  2: '视觉相机调试',
  3: '传送带调试',
  4: '推料气缸调试',
}

const typeMap = {
  // device_id: 1 (光电传感器)
  1: '灵敏度',
  // device_id: 2 (视觉相机)
  2: '分辨率与帧率',
  3: '曝光时间与增益',
  4: '白平衡',
  5: '焦距与对焦',
  6: '变频器参数',
  7: '气缸动作力度',
  8: '气缸动作速度',
  9: '磁性开关位置'
  // device_id: 3 (传送带) - 根据实际需求补充
  // device_id: 4 (推料气缸) - 根据实际需求补充
}

const fetchAndProcessData = async () => {
  loading.value = true
  try {
    const res = await getAllTeachingInfo()
    rawData.value = res.data
    processTableData()
  } catch (error) {
    console.error("Error fetching teaching info for display:", error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const processTableData = () => {
  const processed = []
  const groupedData = {}

  rawData.value.forEach(item => {
    const key = `user_${item.userId}_device_${item.deviceId}`;
    if (!groupedData[key]) {
      groupedData[key] = {
        userId: item.userId,
        deviceId: item.deviceId,
        project: deviceMap[item.deviceId] || '未知项目',
        contents: []
      }
    }
    groupedData[key].contents.push({
      type: item.type,
      content: typeMap[item.type] || '未知内容',
      question: item.question || '',
      answer: item.answer || '',
      remark: '', // 备注字段目前为空，根据需求补充
    });
  });

  Object.values(groupedData).forEach(group => {
    if (group.contents.length === 0) {
      processed.push({
        group: `第${group.userId}组`,
        project: group.project,
        content: '',
        question: '',
        answer: '',
        remark: '',
        spanRow: 1, // 至少一行
        spanCol: 1
      });
    } else {
      group.contents.forEach((contentItem, index) => {
        processed.push({
          group: index === 0 ? `第${group.userId}组` : '',
          project: index === 0 ? group.project : '',
          content: contentItem.content,
          question: contentItem.question,
          answer: contentItem.answer,
          remark: contentItem.remark,
          spanRow: index === 0 ? group.contents.length : 0, // 组别和项目合并行
          spanCol: 1
        });
      });
    }
  });
  tableData.value = processed
}

// 合并单元格的逻辑
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0 || columnIndex === 1) { // 组别和调试项目列
    if (row.spanRow > 0) {
      return { rowspan: row.spanRow, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 }
    }
  }
}

const tableRowClassName = ({ row, rowIndex }) => {
  if (row.group.includes('第一组') || row.group.includes('第三组')) {
    return 'row-white'
  } else if (row.group.includes('第二组') || row.group.includes('第四组')) {
    return 'row-orange'
  }
  return ''
}

// 表头样式
const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  return {
    backgroundColor: '#f5f7fa',
    color: '#606266',
    fontWeight: '600',
    fontSize: '14px',
    textAlign: 'center',
    padding: '12px 0',
    borderBottom: '2px solid #ebeef5'
  }
}

// 单元格样式
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  const styles = {
    padding: '12px 8px',
    fontSize: '14px',
    lineHeight: '1.5',
    color: '#606266',
    textAlign: 'center'  // 所有单元格默认居中
  }

  // 调试项目和调试内容列使用浅蓝色背景
  if (columnIndex === 1 || columnIndex === 2) {
    styles.backgroundColor = '#f0f9ff'
  }

  return styles
}

const clearAllData = () => {
  ElMessageBox.confirm(
    '此操作将永久清空数据库中所有教学信息数据，是否继续？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const res = await clearTeachingTable()
      if (res.data.code === 200) { // 假设后端返回 { code: 200, msg: "成功" }
        ElMessage({
          type: 'success',
          message: '数据已成功清空！',
        })
        fetchAndProcessData() // 清空后重新获取数据以刷新表格
      } else {
        ElMessage({
          type: 'error',
          message: `数据清空失败: ${res.data.msg || '未知错误'}`,
        })
      }
    } catch (error) {
      console.error("Error clearing teaching data:", error)
      ElMessage({
        type: 'error',
        message: '清空数据时发生错误！',
      })
    }
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消清空操作',
    })
  })
}

onMounted(() => {
  fetchAndProcessData()
  refreshInterval = setInterval(fetchAndProcessData, 3000) // 5秒刷新一次
})

onBeforeUnmount(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.teaching-display {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.display-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.display-header {
  margin-bottom: 24px;
  text-align: center;
}

.header-content {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.page-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
  font-weight: 600;
  text-align: center;
}

.header-actions {
  position: absolute;
  right: 0;
  display: flex;
  gap: 12px;
}

.clear-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.table-container {
  margin-top: 16px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.row-white) {
  background-color: #ffffff;
}

:deep(.row-orange) {
  background-color: #fcf4ee;
}

:deep(.content-column) {
  background-color: #f0f9ff;
}

:deep(.record-column) {
  background-color: #ffffff;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table__cell) {
  border-color: #ebeef5;
}

:deep(.el-table .cell) {
  text-align: center !important;
}

:deep(.el-table__body-wrapper .el-table__cell) {
  text-align: center !important;
}

:deep(.el-table__header-wrapper .el-table__cell) {
  text-align: center !important;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  padding: 8px 16px;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.custom-table) {
  .el-table__cell {
    text-align: center !important;
  }
  
  .el-table__header-wrapper {
    .el-table__cell {
      text-align: center !important;
    }
  }
  
  .el-table__body-wrapper {
    .el-table__cell {
      text-align: center !important;
    }
  }
  
  .cell {
    text-align: center !important;
  }
}

@media screen and (max-width: 768px) {
  .teaching-display {
    padding: 12px;
  }

  .display-container {
    padding: 16px;
  }

  .page-title {
    font-size: 20px;
  }

  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style> 